// ================================================
// Builder.Alyr.Net 智能体生成文件 [Builder.Alyr.Net] [2025-07-28]
// (c) 2020-2025 ALYR.NET
// ================================================

const fs = require('fs-extra');
const path = require('path');
const chalk = require('chalk');

/**
 * 自动修复助手
 * @class AutoFixHelper
 * @description 提供文件自动修复功能，包括重命名和添加版权声明
 */
class AutoFixHelper {
  constructor() {
    this.projectRoot = path.resolve(__dirname, '../..');
  }

  /**
   * 修复后端文件命名
   * @param {string} filePath - 文件路径
   * @returns {Promise<boolean>} 修复是否成功
   */
  async fixBackendNaming(filePath) {
    try {
      const fileName = path.basename(filePath);
      const dir = path.dirname(filePath);
      
      // 如果已经有Alyr-前缀，跳过
      if (fileName.startsWith('Alyr-')) {
        console.log(chalk.green(`✅ 文件已符合命名规范: ${fileName}`));
        return true;
      }
      
      // 生成新文件名
      const newFileName = `Alyr-${fileName}`;
      const newFilePath = path.join(dir, newFileName);
      
      // 检查新文件名是否已存在
      if (await fs.pathExists(newFilePath)) {
        console.log(chalk.red(`❌ 目标文件已存在: ${newFileName}`));
        return false;
      }
      
      // 重命名文件
      await fs.move(filePath, newFilePath);
      console.log(chalk.green(`✅ 文件重命名成功: ${fileName} → ${newFileName}`));
      
      return true;
    } catch (error) {
      console.error(chalk.red(`❌ 文件重命名失败: ${error.message}`));
      return false;
    }
  }

  /**
   * 添加版权声明
   * @param {string} filePath - 文件路径
   * @returns {Promise<boolean>} 修复是否成功
   */
  async addCopyright(filePath) {
    try {
      if (!await fs.pathExists(filePath)) {
        console.log(chalk.red(`❌ 文件不存在: ${filePath}`));
        return false;
      }
      
      const content = await fs.readFile(filePath, 'utf8');
      
      // 检查是否已有版权声明
      if (content.includes('© 2020-2025 ALYR.NET')) {
        console.log(chalk.green(`✅ 文件已包含版权声明`));
        return true;
      }
      
      // 生成版权头
      const header = `// ================================================
// Builder.Alyr.Net 智能体生成文件 [Builder.Alyr.Net] [${new Date().toISOString().split('T')[0]}]
// (c) 2020-2025 ALYR.NET
// ================================================`;

`;
      
      // 添加版权头到文件开头
      const newContent = copyrightHeader + content;
      await fs.writeFile(filePath, newContent, 'utf8');
      
      console.log(chalk.green(`✅ 版权声明添加成功: ${path.basename(filePath)}`));
      return true;
    } catch (error) {
      console.error(chalk.red(`❌ 添加版权声明失败: ${error.message}`));
      return false;
    }
  }

  /**
   * 批量修复文件
   * @param {Array<string>} filePaths - 文件路径数组
   * @param {string} fixType - 修复类型: 'naming' | 'copyright' | 'both'
   * @returns {Promise<Object>} 修复结果统计
   */
  async batchFix(filePaths, fixType = 'both') {
    const results = {
      success: 0,
      failed: 0,
      skipped: 0,
      details: []
    };

    for (const filePath of filePaths) {
      const fileName = path.basename(filePath);
      console.log(chalk.blue(`🔧 正在修复: ${fileName}`));
      
      try {
        let fixed = false;
        
        if (fixType === 'naming' || fixType === 'both') {
          const namingFixed = await this.fixBackendNaming(filePath);
          if (namingFixed) fixed = true;
        }
        
        if (fixType === 'copyright' || fixType === 'both') {
          const copyrightFixed = await this.addCopyright(filePath);
          if (copyrightFixed) fixed = true;
        }
        
        if (fixed) {
          results.success++;
          results.details.push({ file: fileName, status: 'success' });
        } else {
          results.skipped++;
          results.details.push({ file: fileName, status: 'skipped' });
        }
      } catch (error) {
        results.failed++;
        results.details.push({ file: fileName, status: 'failed', error: error.message });
      }
    }

    // 输出修复报告
    console.log(chalk.cyan(`\n📊 修复完成报告:`));
    console.log(chalk.green(`✅ 成功: ${results.success} 个文件`));
    console.log(chalk.yellow(`⏭️  跳过: ${results.skipped} 个文件`));
    console.log(chalk.red(`❌ 失败: ${results.failed} 个文件`));

    return results;
  }

  /**
   * 交互式修复单个文件
   * @param {string} filePath - 文件路径
   * @param {string} issueType - 问题类型: 'naming' | 'copyright'
   */
  async interactiveFix(filePath, issueType) {
    const fileName = path.basename(filePath);
    
    console.log(chalk.cyan(`\n🔧 自动修复助手`));
    console.log(chalk.white(`文件: ${fileName}`));
    console.log(chalk.white(`问题: ${issueType === 'naming' ? '命名不规范' : '缺少版权声明'}`));
    
    if (issueType === 'naming') {
      const success = await this.fixBackendNaming(filePath);
      if (success) {
        console.log(chalk.green(`🎉 文件命名修复完成！`));
      }
    } else if (issueType === 'copyright') {
      const success = await this.addCopyright(filePath);
      if (success) {
        console.log(chalk.green(`🎉 版权声明添加完成！`));
      }
    }
  }
}

module.exports = AutoFixHelper;